package com.jframe.sys.controller.utils;

import java.util.ArrayList;
import java.util.Random;

import javax.servlet.http.HttpSession;

public class Token {

	private static String TOKEN_LIST="tokenList";
	public static String TOKEN_NAME="tokenName";
	
	private static ArrayList getTokenList(HttpSession session){	
		if(session!=null){
			Object obj = session.getAttribute(TOKEN_LIST);
			return (ArrayList)obj;
		}else{
			ArrayList list = new ArrayList();
			session.setAttribute(TOKEN_LIST, list);
			return list;
		}
	}
	
	private static void saveToken(HttpSession session,String token){
		ArrayList list = getTokenList(session);
		list.add(token);
		session.setAttribute(TOKEN_LIST, list);
	}
	
	private static String generateToken(){
		return getRandomString(10)+new Long(System.currentTimeMillis()).toString()+getRandomString(10);
	}
	
	public static String getTokenString(HttpSession session){
		String token = generateToken();
		saveToken(session, token);
		return token;
	}
	
	public static boolean isTokenValid(HttpSession session,String token){
		boolean isValid = false;
		ArrayList list = getTokenList(session);
		if(list.contains(token)){
			isValid=true;
			list.remove(token);
		}
		return isValid;
	}
	
	/**
	 * 获取长度为length的随机字符串0-9,a-z,A-Z
	 * @param length(字符长度)
	 * @return
	 */
	public static String getRandomString(int length) { 
	    StringBuffer buffer = new StringBuffer("zAwYoIFj0vRLQPGHgTxbO8aUV1nEuKcWsiMNh7Bp4qJyCDr6Z92Skl3mdt5Xef"); 
	    StringBuffer sb = new StringBuffer(); 
	    Random r = new Random(); 
	    int range = buffer.length(); 
	    for (int i = 0; i < length; i ++) { 
	        sb.append(buffer.charAt(r.nextInt(range))); 
	    } 
	    return sb.toString(); 
	}

	/**
	 *  获取token input hidden Html
	 * @param session
	 * @return
	 */
	public static String getTokenHTML(HttpSession session){
		StringBuffer sb = new StringBuffer();
		sb.append("<input type='hidden' name='");
		sb.append(TOKEN_NAME);
		sb.append("' value='");
		sb.append(getTokenString(session));
		sb.append("' />");
		return sb.toString();
	}
	
}
